package org.dut.community.quartz;

import lombok.extern.slf4j.Slf4j;
import org.dut.community.entity.DiscussPost;
import org.dut.community.service.DiscussPostService;
import org.dut.community.service.ElasticsearchService;
import org.dut.community.service.LikeService;
import org.dut.community.util.CommunityConstant;
import org.dut.community.util.RedisKeyUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Component
public class PostScoreRefreshJob implements Job, CommunityConstant {
    @Autowired
    private RedisTemplate redisTemplate; // 用于操作Redis的模板
    @Autowired
    private DiscussPostService discussPostService; // 更新帖子分数
    @Autowired
    private LikeService likeService; // 查询点赞数
    @Autowired
    private ElasticsearchService elasticsearchService; // 同步es

    private static final Date startDate;

    static {
        try {
            startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2025-09-09 00:00:00");
        } catch (Exception e) {
            throw new RuntimeException("初始化网站创建时间失败", e);
        }
    }


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String redisKey = RedisKeyUtil.getPostScoreKey();
        BoundSetOperations operations = redisTemplate.boundSetOps(redisKey);
        Long size = operations.size();

        if (size == null || size == 0) {
            log.info("没有需要刷新分数的帖子！定时任务取消");
            return;
        }
        log.info("开始刷新帖子分数，帖子数量：{}", size);
        while (size > 0) {
            Integer postId = (Integer) operations.pop();
            if (postId != null) {
                log.info("刷新帖子分数：id = {}", postId);
                refresh(postId);
            }
            size = operations.size();
        }
        log.info("帖子分数刷新完成");
    }

    private void refresh(int postId) {
        DiscussPost post = discussPostService.findDiscussPostById(postId);
        if (post == null) {
            log.info("该帖子不存在！postId = {}", postId);
            return;
        } else if (post.getStatus() == 2) {
            log.info("该帖子已被删除！postId = {}", postId);
            return;
        }
        // 加精
        boolean isWonderful = post.getStatus() == 1;
        // 评论数
        int commentCount = post.getCommentCount();
        // 点赞数
        long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, postId);
        // 浏览数
        String redisKey = RedisKeyUtil.getPostReadKey(postId);
        Integer readCountInteger = (Integer) redisTemplate.opsForValue().get(redisKey);
        long readCount = 0;
        if (readCountInteger != null) {
            readCount = readCountInteger.longValue();
        }

        // 计算分数
        double weight = (isWonderful ? 75 : 0) + commentCount * 10 + likeCount * 2 + readCount * 0.1;
        double score = Math.log10(Math.max(weight,1)) // 避免出现负数
                + (double) (post.getCreateTime().getTime() - startDate.getTime()) / (1000 * 3600 * 24);
        // 更新帖子分数
        discussPostService.updateScore(postId, score);
        // 同步es
        elasticsearchService.saveDiscussPost(post);

    }
}
